/*
 * @Description: 
 * @Version: 2.0
 * @Date: 2024-04-09 15:03:16
 * @LastEditTime: 2024-04-09 15:16:08
 */

import axios from "axios";
import type {
  AxiosInstance,
  AxiosResponse,
  AxiosError,
} from "axios";
import { getCookie, setCookie } from "../utils/cookie";

const MyReq: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_API_BASEURL,
  timeout: 5000,
  headers: {
    "Content-Type": "application/json",
  },
});

// axios实例拦截请求
MyReq.interceptors.request.use(
  (config: any) => {
    const token = getCookie("token");
    if (token) {
      config.headers.token = token;
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);
// axios实例拦截响应
MyReq.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status === 200) {
      return response;
    }
    return response;
  },
  // 请求失败
  (error: any) => {
    const { response } = error;
    if (response) {
      // 请求已发出，但是不在2xx的范围
      return Promise.reject(response.data);
    }
  }
);

export default MyReq

/***
 * post 方法封装
 */
export function postMethod<T>(url: string, params?: any): Promise<T> {
  return new Promise((resolve, reject) => {
    MyReq.post(url, params)
      .then((res: any) => {
        if (res.data.code === 200 && res.headers["token"]) {
          setCookie("token", res.headers["token"], 21600);
        }
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
/***
 * get 方法封装
 */
export function getMethod<T>(url: string, params?: any): Promise<T> {
  return new Promise((resolve, reject) => {
    MyReq.get(url, params)
      .then((res: any) => {
        if (res.data.code === 200 && res.headers["token"]) {
          setCookie("token", res.headers["token"], 21600);
        }
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
/**
 * 文件上传 方法封装
 * 上传文件传参方式注意为form-data格式
 */
export function uploadFile<T>(url: string, uploadForm: any): Promise<T> {
  const fd = new FormData();
  fd.append("fileName", uploadForm.projectId);
  fd.append("file", uploadForm.file);
  return new Promise((resolve, reject) => {
    MyReq.post(url, fd, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    })
      .then((res: any) => {
        if (res.data.code === 200 && res.headers["token"]) {
          setCookie("token", res.headers["token"], 21600);
        }
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
